import React, { useState, useEffect, useRef } from "react";
import styled from "@emotion/styled";
import Instructions from "components/instructions/index";
import {
  Space,
  Select,
  Button,
  Table,
  Input,
  Upload,
  Tooltip,
  Modal,
  Form,
  message,
} from "antd";
import { useDebounce, getCurrent, downUrl } from "utils/help";
import {
  getDataList,
  getDataQuery,
  importFile,
  exportFile,
  addData,
} from "api";
import { SyncOutlined, PlusOutlined, MinusOutlined } from "@ant-design/icons";

const { Option } = Select;
export default function Database() {
  const [filter, setFilter] = useState({
    current: 1,
    pageSize: 10,
    key: "",
    value: "",
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState([]);
  const [key, setKey] = useState("");
  const [value, setValue] = useState("");

  const [visible, setVisible] = useState(false);
  const [isRequest, setIsRequest] = useState(false);
  const editForm = useRef();
  const [keysList, setKeysList] = useState([]);
  const newFilter = useDebounce(filter, 500);
  useEffect(() => {
    getList(newFilter);
  }, [newFilter]);

  const getList = (params: any) => {
    getDataList(params).then((res: any) => {
      setList(res.list);
      setTotal(res.totalCount);
    });
  };

  useEffect(() => {
    getDataQuery().then((res: any) => {
      setKeysList(res);
    });
  }, []);

  const changeFile = (val: any) => {
    let formData = new FormData();
    formData.append("file", val.file.originFileObj);
    message.loading("文件导入中，请稍后……");
    importFile(formData)
      .then((res) => {
        message.success("导入成功!");
        message.destroy();
        getList(filter);
      })
      .catch((err) => {
        message.destroy();
        message.error("导入失败");
      });
  };

  const downFile = () => {
    exportFile({
      key,
      value,
    }).then((res) => {
      downUrl(res);
    });
  };

  const addDatabase = (val: any) => {
    addData(val).then((res) => {
      message.success("新增成功！");
      setVisible(false);
      getList(filter);
    });
  };

  const columns = [
    {
      title: "id",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "equip_type",
      dataIndex: "equip_type",
      key: "equip_type",
    },
    {
      title: "equip_catagory",
      dataIndex: "equip_catagory",
      key: "equip_catagory",
    },
    {
      title: "descript",
      dataIndex: "descript",
      key: "descript",
    },
    {
      title: "desc_key",
      dataIndex: "desc_key",
      key: "desc_key",
    },
    {
      title: "answer",
      dataIndex: "answer",
      key: "answer",
    },
  ];
  return (
    <div style={{ padding: 10 }}>
      <Wrapper>
        <Instructions title="数据列表" hideSearch={true} />
        <div style={{ padding: 16, borderTop: "1px solid #f0f0f0" }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <Space>
              查找
              <Select
                style={{ width: 200 }}
                placeholder="请选择查询字段"
                onChange={(val: any) => setKey(val)}
              >
                {keysList.map((item, idx) => {
                  return (
                    <Option key={idx} value={item}>
                      {item}
                    </Option>
                  );
                })}
              </Select>
              <Input
                placeholder="请输入查询内容"
                onChange={(e) => setValue(e.target.value)}
              ></Input>
              <Button
                onClick={() => {
                  setFilter({
                    ...filter,
                    key: "",
                    value: "",
                  });
                  setKey("");
                  setValue("");
                }}
              >
                重置
              </Button>
              <Button
                type="primary"
                onClick={() =>
                  setFilter({
                    ...filter,
                    key,
                    value,
                  })
                }
              >
                查询
              </Button>
            </Space>
            <Space>
              <Upload
                customRequest={() => {}}
                maxCount={1}
                showUploadList={false}
                onChange={(val) => changeFile(val)}
              >
                <Button type="primary">导入</Button>
              </Upload>
              <Button onClick={() => downFile()} type="primary">
                导出
              </Button>
            </Space>
          </div>
          <div style={{ marginTop: 20 }}>
            <Space>
              <Tooltip title="刷新">
                <Button
                  onClick={() => getList(filter)}
                  type="text"
                  size="small"
                >
                  <SyncOutlined />
                </Button>
              </Tooltip>
              <Tooltip title="新增">
                <Button
                  type="text"
                  size="small"
                  onClick={() => {
                    setVisible(true);
                  }}
                >
                  <PlusOutlined />
                </Button>
              </Tooltip>
              <Tooltip title="删除">
                <Button
                  type="text"
                  size="small"
                  onClick={() => {
                    setVisible(true);
                  }}
                >
                  <MinusOutlined />
                </Button>
              </Tooltip>
            </Space>
          </div>
          <div style={{ marginTop: 30 }}>
            <Table
              dataSource={list}
              columns={columns}
              rowKey="id"
              pagination={{
                ...filter,
                total,
                onChange: (page, size?: number) =>
                  setFilter({
                    ...filter,
                    current: page,
                    pageSize: size ? size : filter.pageSize,
                  }),
              }}
            />
          </div>
        </div>
        <Modal
          title="新增数据"
          visible={visible}
          cancelText="取消"
          okText="确定"
          okButtonProps={{
            disabled: isRequest,
          }}
          width={700}
          destroyOnClose={true}
          // @ts-ignore
          onOk={() => editForm.current.submit()}
          onCancel={() => setVisible(false)}
        >
          <Form
            labelCol={{
              span: 24,
            }}
            wrapperCol={{
              span: 24,
            }}
            onFinish={(val) => addDatabase(val)}
            // @ts-ignore
            ref={editForm}
          >
            <Form.Item label="equip_type" name="equip_type">
              <Input autoComplete="off" />
            </Form.Item>
            <Form.Item label="equip_catagory" name="equip_catagory">
              <Input autoComplete="off" />
            </Form.Item>
            <Form.Item
              label="descript"
              name="descript"
              rules={[{ required: true, message: "请输入descript!" }]}
            >
              <Input placeholder="请输入业务名称" autoComplete="off" />
            </Form.Item>
            <Form.Item label="desc_key" name="desc_key">
              <Input autoComplete="off" />
            </Form.Item>
            <Form.Item label="answer" name="answer">
              <Input autoComplete="off" />
            </Form.Item>
          </Form>
        </Modal>
      </Wrapper>
    </div>
  );
}

const Wrapper = styled.div`
  background-color: #fff;
  height: calc(100vh - 85px);
  overflow-y: auto;
  border-radius: 4px;
`;
